var express = require('express');
var router = express.Router();

// 自定义模块
const query = require('../../utils/mysql');
const Result = require('../../utils/api');

var checkAuth = require('../../utils/checkAuth')

// 作品 / 链接 列表
router.post('/demo/list', async function (req, res, next) {
    let params = req.body
    try {
        let sql = "SELECT id,name,link,`describe`,avatar,add_time,is_show,is_demo FROM blog_links WHERE is_demo = ? AND is_del = ? LIMIT ?,?"
        let sqlArr = [params.is_demo, 0, (params.page - 1) * params.limit, params.limit]
        let demoData = await query(sql, sqlArr)
        let countSql = "SELECT COUNT(0) as count FROM blog_links WHERE is_demo = ? AND is_del = 0"
        let countArr = [params.is_demo]
        let [{ count }] = await query(countSql, countArr)
        Result.success(res, { data: Array.from(demoData), count: count })
    } catch (error) {
        console.log(error);
    }

})

// 作品 / 链接 显示
router.post('/demo/show', checkAuth, async function (req, res, next) {
    let params = req.body
    try {
        let sql = "UPDATE blog_links SET is_show = ? WHERE id = ?"
        let sqlArr = [params.is_show, params.id]
        await query(sql, sqlArr)
        Result.success(res, 'SUCCESS', "操作成功")
    } catch (error) {
        Result.fail(res, '操作失败')
    }
})

// 作品 / 链接 删除
router.post('/demo/delete', checkAuth, async function (req, res, next) {
    let params = req.body
    try {
        let sql = "UPDATE blog_links SET is_del = 1 WHERE id = ?"
        let sqlArr = [params.id]
        await query(sql, sqlArr)
        Result.success(res, "SUCCESS", "删除成功")
    } catch (error) {
        Result.fail(res, "删除失败")
    }
})

// 作品 / 链接 添加
router.post('/demolink/add', checkAuth, async function (req, res, next) {
    console.log(req.body.is_demo);
    let params = req.body,
        str1 = params.is_demo ? '作品' : '链接',
        str2 = params.id ? '更新' : '添加',
        success = str1 + str2 + '成功',
        fail = str1 + str2 + '失败',
        sql,
        sqlArr;
    if (!params.id) {
        sql = "INSERT INTO blog_links (`name`,link,`describe`,avatar,add_time,is_demo,is_show,is_del) VALUES (?,?,?,?,?,?,?,?)"
        sqlArr = [params.name, params.link, params.describe, params.avatar, new Date(), params.is_demo, params.is_show, 0]
    } else {
        sql = "UPDATE blog_links SET `name`=?, link=?, `describe`=?, avatar=?,is_show = ? WHERE id = ?"
        sqlArr = [params.name, params.link, params.describe, params.avatar, params.is_show, params.id]
    }

    console.log(success);
    try {
        await query(sql, sqlArr)
        Result.success(res, 'SUCCESS', success)
    } catch (error) {
        console.log(error);
        Result.fail(res, fail)
    }

})

module.exports = router;